#include "qtch/qtch.h"

static qtch::Logger::ptr logger = QTCH_LOG_NAME("test");
static qtch::Logger::ptr logger2 = QTCH_LOG_NAME("system");

void test_time(){
    qtch::IOManager::getThis()->addTimer(1000,[](){
        QTCH_LOG_DEBUG(logger) << "timer";
    },true);
}

void run(){
    logger->setLevel(qtch::LogLevel::INFO);
    logger2->setLevel(qtch::LogLevel::INFO);
    qtch::http::HttpServer::ptr server(new qtch::http::HttpServer(true));
    qtch::http::ServletDispath::ptr sd = server->getServletdispatch();
    sd->addServlet("/qtch/xx", [](qtch::http::HttpRequest::ptr request
                    , qtch::http::HttpResponse::ptr response
                    , qtch::http::HttpSession::ptr session) {
        QTCH_LOG_DEBUG(logger) << "recv path:/qtch/xx \n" << request;
        response->setBody(request->toString()); 
        return 0;
    });
    sd->addServlet("/", [](qtch::http::HttpRequest::ptr request
                    , qtch::http::HttpResponse::ptr response
                    , qtch::http::HttpSession::ptr session) {
        std::string content = "<!doctype html><html lang=\"zxx\">\n<head>\n<meta charset=\"utf-8\">\n<link rel=\"icon\" href=\"/favicon.ico\" type=\"image/x-icon\">\n</head>\n<body>\ntest\n</body>\n</html>";
        response->setBody(content); 
        return 0;
    });
    sd->addGlobServlet("/qtch/xx*", [](qtch::http::HttpRequest::ptr request
                    , qtch::http::HttpResponse::ptr response
                    , qtch::http::HttpSession::ptr session) {
        QTCH_LOG_DEBUG(logger) << "recv path:/qtch/xx \n" << request;
        response->setBody("/qtch/xx*"); 
        return 0;
    });
    sd->addServlet("/favicon.ico", [](qtch::http::HttpRequest::ptr request
                    , qtch::http::HttpResponse::ptr response
                    , qtch::http::HttpSession::ptr session) {
        qtch::ByteArray::ptr ba(new qtch::ByteArray);
        ba->readFromFile("/home/qiu/qtch/images/favicon.ico");
        std::string content = ba->toString();
        response->setHeader("content-type","image/x-icon");
        response->setBody(content); 
        return 0;
    });
    qtch::Address::ptr addr = qtch::Address::LookupAny("0.0.0.0:8020");
    while(!server->bind(addr,false)){
        sleep(2);
    }
    bool rt = server->loadCertificates("/home/qiu/qtch/Certificate/server.crt"
            ,"/home/qiu/qtch/Certificate/server_rsa_private.pem.unsecure");
    if(!rt){
        QTCH_LOG_DEBUG(logger) << "loadCertificates faile";
        return;
    }
    server->start();
}

int main(){
    qtch::IOManager iom(2);
    iom.schedule(run);
    // iom.schedule(test_time);
    iom.start();
}